import {
	defineStore
} from 'pinia'

export const useTabsStore = defineStore('tabs', {
	state: () => ({
		tabs: [{
			title: '首页',
			name: '1',
			path: '/home',
			fixed: true
		}],
		activeTab: '1',
		tabIndex: 2
	}),
	actions: {
		addTab(route) {
			const existingTab = this.tabs.find(tab => tab.path === route.path)
			if (existingTab) {
				this.activeTab = existingTab.name
				return existingTab
			}

			const newTabName = `${++this.tabIndex}`
			const newTab = {
				title: route.meta?.title || route.name,
				name: newTabName,
				path: route.path,
				content: route.meta?.title || route.name
			}

			this.tabs.push(newTab)
			this.activeTab = newTabName
			return newTab
		},

		removeTab(targetName) {
			const tabToRemove = this.tabs.find(tab => tab.name === targetName)
			if (tabToRemove?.fixed) return false

			const currentIndex = this.tabs.findIndex(tab => tab.name === targetName)
			const tabs = this.tabs.filter(tab => tab.name !== targetName)

			// 确定新的激活标签
			let newActiveTab = null

			// 优先选择前一个标签
			if (currentIndex > 0) {
				newActiveTab = tabs[currentIndex - 1]
			}
			// 如果没有前一个标签，选择后一个标签
			else if (tabs.length > currentIndex) {
				newActiveTab = tabs[currentIndex]
			}
			// 如果都没有，选择首页
			else {
				newActiveTab = tabs.find(tab => tab.fixed)
			}

			this.tabs = tabs
			this.activeTab = newActiveTab.name

			return newActiveTab.path
		},

		initFromRoute(route) {
			// 确保首页存在
			if (!this.tabs.some(tab => tab.fixed)) {
				this.tabs.unshift({
					title: '首页',
					name: '1',
					path: '/home',
					fixed: true
				})
			}

			// 添加当前路由对应的标签
			if (route.meta?.tab && route.path !== '/home') {
				this.addTab(route)
			} else {
				this.activeTab = '1'
			}
		}
	},
	persist: {
		enabled: true,
		strategies: [{
			key: 'tabs_state',
			storage: localStorage
		}]
	}
})